<?php

/**
 * Memcache backend for the phpCacheTag library
 *
 * @package phpCacheTag
 * @author Umkus
 * @version 0.1
 */
class MemcacheTag extends CacheTag
{
 /**
  * 
  * @var Memcache
  */
	private $memcache_obj;

	/**
	 * Initialises memcache
	 *
	 * @return boolean
	 */
	public function __construct()
	{
		if (!class_exists('Memcache'))
		{
			throw new Exception('Memcache is not installed');
		}

		$memcache_obj = new Memcache();

		@$memcache_obj->connect('127.0.0.1', 11211);

		if (!@$memcache_obj->getServerStatus('127.0.0.1', 11211))
		{
			throw new Exception('Memcache not running?');
		}

		$this->memcache_obj = $memcache_obj;

		//Parent constructor has to be called
		parent::__construct();

		return true;
	}

	/**
	 * Returns value of the variable in cache
	 *
	 * @return	mixed
	 */
	protected function Get($name)
	{
		return $this->memcache_obj->get($name);
	}

  /**
   * Replaces a value of the variable by name
   *
   * @param string $name
   * @param mixed $value
   * @return mixed
   */
	protected function Replace($name, $value)
	{
		return $this->memcache_obj->replace($name, $value, 0, 0);
	}

	/**
	 * Deletes variable in cache
	 *
	 * @param	string	$name
	 * @return boolean
	 */
	protected function Delete($name)
	{
		return $this->memcache_obj->delete($name);
	}

	/**
	 * Adds/replaces variable in cache
	 *
	 * @param	string $varName
	 * @param	mixed	$value
	 * @param	int	$timeoutMinutes 	minutes to store data
	 * @return mixed
	 */
	protected function Set($varName, $value, $timeoutMinutes = 0)
	{
		return $this->memcache_obj->set($varName, $value,/* MEMCACHE_COMPRESSED*/0, 60 * $timeoutMinutes); // Memcache needs seconds
	}
}